package com.movies.service.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.User;
import com.movies.service.service.UserService;
import com.movies.service.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.hutool.crypto.SecureUtil;
import com.movies.service.entity.Admin;
import com.movies.service.mapper.AdminMapper;


@RestController
@RequestMapping("/admin/user")
@SaCheckLogin
@SaCheckRole("ADMIN")
public class AdminUserController {

    @Autowired
    private UserService userService; // 仅用于分页
    @Autowired
    private UserMapper userMapper;   // 原生 SQL CRUD
    @Autowired
    private AdminMapper adminMapper;   // 管理员原生 SQL CRUD

//    分页查询用户列表（支持按用户名/邮箱/状态筛选）
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String uname,
                       @RequestParam(required = false) String email,
                       @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(uname != null && !uname.isEmpty(), User::getUname, uname)
                .like(email != null && !email.isEmpty(), User::getEmail, email)
                .eq(status != null, User::getStatus, status);
        Page<User> page = userService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success("查询成功", page);
    }

//    根据ID获取用户详情
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        return Result.success(userMapper.selectUserById(id));
    }

//    新增用户
    @PostMapping
    public Result create(@RequestBody User user) {
      // 密码加密（保持与登录一致：MD5）
      if (user.getPassword() != null && !user.getPassword().isEmpty()) {
        user.setPassword(SecureUtil.md5(user.getPassword()));
      }
      String role = String.valueOf(user.getRole());
      // 如果角色为管理员，则写入管理员表
      if ("ADMIN".equalsIgnoreCase(role)) {
        Admin admin = new Admin();
        admin.setAname(user.getUname());
        admin.setPassword(user.getPassword());
        admin.setPhone(user.getPhone());
        admin.setEmail(user.getEmail());
        admin.setStatus(user.getStatus() != null ? user.getStatus() : 1);
        admin.setRole("ADMIN");
        int rows = adminMapper.insertAdmin(admin);
        return rows > 0 ? Result.success("新增成功（管理员）") : Result.error(Constants.CODE_600, "新增失败（管理员）");
      }
      // 否则写入用户表
      int rows = userMapper.insertUser(user);
      return rows > 0 ? Result.success("新增成功") : Result.error(Constants.CODE_600, "新增失败");
    }

//    更新用户信息
    @PutMapping
    public Result update(@RequestBody User user) {
        int rows = userMapper.updateUserById(user);
        return rows > 0 ? Result.success("更新成功") : Result.error(Constants.CODE_600, "更新失败");
    }

//    删除用户
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        int rows = userMapper.deleteUserById(id);
        return rows > 0 ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

//    批量删除用户
    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody java.util.List<Long> ids) {
        int rows = userMapper.deleteUsersByIds(ids);
        return rows > 0 ? Result.success("批量删除成功") : Result.error(Constants.CODE_600, "批量删除失败");
    }
}